import {
  deleteCodeTableUsingDelete,
  fileInputUsingPost,
  getCodeTableByIdUsingGet,
  listCodeTablesUsingGet,
  updateCodeTableStatusBatchUsingPut,
  updateCodeTableStatusUsingPut,
} from '@/services/data-factory/mabiaoguanli';
import type { ProColumns } from '@ant-design/pro-components';
import { ActionType, ProTable } from '@ant-design/pro-components';
import { App, Button, message, Popconfirm, Space, Tag } from 'antd';
import { useRef, useState } from 'react';
import CodeForm from './components/CodeForm';
import './index.less';

interface DataItem {
  codeNumber: number;
  codeId: number;
  codeName: string;
  codeExplain: string;
  status: string;
  updateTime: string;
  codeValueTables: [];
}
const CodeStandard: React.FC = () => {
  const [formVisible, setFormVisible] = useState(false);
  const [editData, setEditData] = useState<any>(null);
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  // 简化删除处理函数
  const handleDelete = async (codeId: number) => {
    try {
      const res = await deleteCodeTableUsingDelete({ codeId });
      if (res.code === 100200) {
        message.success('删除成功');
      } else {
        message.error(res.msg || '删除失败');
      }
    } catch (error) {
      message.error('删除失败');
    }
    actionRef.current?.reload();
  };

  const handleEdit = async (record: DataItem) => {
    try {
      const res = await getCodeTableByIdUsingGet({ codeId: record.codeId });
      console.log('根据id返回的数据', res);
      if (res.code === 100200 && res.data) {
        // 转换数据格式
        const editData = {
          codeId: record.codeId,
          codeName: record.codeName,
          codeExplain: record.codeExplain,
          codeValueList: res.data.codeValueTables.map((item: any) => ({
            codeTableId: item.codeTableId, // 直接使用每个码值的 codeTableId
            codeValue: item.codeValue,
            codeValueName: item.codeValueName,
            codeValueMean: item.codeValueMean || '',
          })),
          codeTableId: res.data.codeValueTables[0]?.codeTableId || 0, // 只取第一个码值的 codeTableId
        };
        setEditData(editData);
        setFormVisible(true);
      }
    } catch (error) {
      message.error('获取数据失败');
    }
  };

  // 简化状态更新处理函数
  const handleUpdateStatus = async (codeId: number, newStatus: string) => {
    try {
      const res = await updateCodeTableStatusUsingPut({ codeId });
      console.log('更新状态返回的数据', res);

      if (res.code === 100200) {
        message.success(`${newStatus === '已发布' ? '发布' : '停用'}成功`);
        actionRef.current?.reload();
      } else {
        message.error(res.msg || '操作失败');
      }
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 添加批量操作函数
  const handleBatchUpdateStatus = async (newStatus: string) => {
    try {
      if (selectedRowKeys.length === 0) {
        message.warning('请选择要操作的码表');
        return;
      }
      const res = await updateCodeTableStatusBatchUsingPut(selectedRowKeys);
      if (res.code === 100200) {
        message.success(`批量${newStatus === '已发布' ? '发布' : '停用'}成功`);
        actionRef.current?.reload();
        actionRef.current?.clearSelected?.();
      } else {
        message.error(res.msg || '操作失败');
      }
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 修改下载模板函数
  const handleDownloadTemplate = () => {
    window.location.href = '/api/codeTable/downloadTemplate';
  };

  // 修改文件上传函数
  const handleFileUpload = async (e: Event) => {
    const file = (e.target as HTMLInputElement).files?.[0];
    if (!file) return;

    const formData = new FormData();
    formData.append('file', file);

    try {
      // 调用 fileInputUsingPost，传递 formData 作为 body
      const res = await fileInputUsingPost({ formData }, file);

      if (res.code === 100200) {
        message.success('导入成功');
        actionRef.current?.reload();
      } else {
        message.error(res.msg || '导入失败');
      }
    } catch (error) {
      console.error('上传错误:', error);
      message.error('导入失败');
    }
  };

  // 然后定义 columns
  const columns: ProColumns<DataItem>[] = [
    {
      title: '码表编号',
      dataIndex: 'codeNumber',
      width: 200,
      search: false,
    },
    {
      title: '码表名称',
      dataIndex: 'codeName',
      fieldProps: {
        placeholder: '请输入码表名称',
      },
      search: true,
    },
    {
      title: '码表说明',
      dataIndex: 'codeExplain',
      search: false,
    },
    {
      title: '码表状态',
      dataIndex: 'status',
      valueEnum: {
        未发布: {
          text: <Tag color="warning">未发布</Tag>,
        },
        已发布: {
          text: <Tag color="success">已发布</Tag>,
        },
        已停用: {
          text: <Tag color="error">已停用</Tag>,
        },
      },
      fieldProps: {
        placeholder: '请选择码表状态',
      },
      search: true,
      render: (_, record) => {
        const statusColorMap: Record<string, string> = {
          未发布: 'warning',
          已发布: 'success',
          已停用: 'error',
        };
        return <Tag color={statusColorMap[record.status]}>{record.status}</Tag>;
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      search: false,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      search: false,
      render: (_, record) => {
        const { status, codeId } = record;
        return (
          <Space>
            {status === '未发布' && (
              <>
                <Popconfirm
                  title="确定要发布这个码表吗？"
                  onConfirm={() => handleUpdateStatus(record.codeId, '已发布')}
                  okText="确认"
                  cancelText="取消"
                >
                  <Button type="link">发布</Button>
                </Popconfirm>
                <Button type="link" onClick={() => handleEdit(record)}>
                  编辑
                </Button>
                <Popconfirm
                  title="确定要删除这个码表吗？"
                  onConfirm={() => handleDelete(codeId)}
                  okText="确认"
                  cancelText="取消"
                >
                  <Button type="link">删除</Button>
                </Popconfirm>
              </>
            )}
            {status === '已发布' && (
              <Button
                type="link"
                onClick={() => handleUpdateStatus(record.codeId, '已停用')}
              >
                停用
              </Button>
            )}
            {status === '已停用' && (
              <>
                <Popconfirm
                  title="确定要发布这个码表吗？"
                  onConfirm={() => handleUpdateStatus(record.codeId, '已发布')}
                  okText="确认"
                  cancelText="取消"
                >
                  <Button type="link">发布</Button>
                </Popconfirm>
                <Button type="link" onClick={() => handleEdit(record)}>
                  编辑
                </Button>
              </>
            )}
          </Space>
        );
      },
    },
  ];

  return (
    <App>
      <ProTable<DataItem>
        columns={columns}
        search={{
          labelWidth: 'auto',
          defaultCollapsed: true,
          searchText: '查询',
          resetText: '重置',
        }}
        toolbar={{
          menu: {
            type: 'inline',
            items: [
              {
                key: 'batchPublish',
                label: (
                  <Button onClick={() => handleBatchUpdateStatus('已发布')}>
                    批量发布
                  </Button>
                ),
              },
              {
                key: 'batchDisable',
                label: (
                  <Button onClick={() => handleBatchUpdateStatus('已停用')}>
                    批量停用
                  </Button>
                ),
              },
            ],
          },
          actions: [
            <Button
              key="template"
              type="primary"
              onClick={handleDownloadTemplate}
            >
              码表模板下载
            </Button>,
            <Button
              key="import"
              type="primary"
              onClick={() => {
                const input = document.createElement('input');
                input.type = 'file';
                input.accept = '.xlsx,.xls';
                input.style.display = 'none';
                input.onchange = handleFileUpload;
                document.body.appendChild(input);
                input.click();
                input.remove();
              }}
            >
              码表导入
            </Button>,
            <Button
              key="add"
              type="primary"
              onClick={() => setFormVisible(true)}
            >
              新增码表
            </Button>,
          ],
        }}
        pagination={{
          defaultPageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
          pageSizeOptions: ['10', '20', '50', '100'],
        }}
        request={async ({ current, pageSize, ...params }) => {
          try {
            const res = await listCodeTablesUsingGet({
              pageNo: current || 1,
              pageSize: pageSize || 10,
              status: params?.status || '',
              codeName: params?.codeName || '',
            });

            return {
              data: res.data?.records || [],
              success: res.code === 100200,
              total: res.data?.total || 0,
            };
          } catch (error) {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        rowSelection={{
          selectedRowKeys,
          onChange: (keys) => setSelectedRowKeys(keys as number[]),
        }}
        rowKey="codeId"
        actionRef={actionRef}
      />

      <CodeForm
        open={formVisible}
        editData={editData}
        onCancel={() => {
          setFormVisible(false);
          setEditData(null);
        }}
        onSuccess={() => {
          setFormVisible(false);
          setEditData(null);
          actionRef.current?.reload();
        }}
      />
    </App>
  );
};

export default CodeStandard;
